# coding=utf-8
# 代码文件：code/chapter27/27.4.1/6.访问静态文件/ch26.4.6.py
import random

from flask import Flask, render_template, request

app = Flask(__name__)
captcha_list = ('rge7o', 'jh5z0', '5hked', 'pywpn')
captcha = 'rge7o'


@app.route('/')
def index():
    # 生成验证码
    gencaptcha()
    return render_template('index.html')


@app.route('/captcha')
def getcaptcha():
    return render_template('index.html', img=captcha)


@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        login_form = request.form

        userid = login_form['userid']
        userpwd = login_form['userpwd']
        vcode = login_form['vcode']
        print('身份证号:', userid)
        print('密码:', userpwd)
        print('验证码:', vcode)

        if vcode.lower() != captcha.lower():
            print('验证码输入错误！')
            print('用户输入的验证码：{1} ，服务器生成的验证码：{1} !'.format(vcode.lower(), captcha.lower()))
            # 重新生成验证码
            gencaptcha()
            return render_template('index.html', img=captcha, message='验证码输入错误！')
        else:
            if userid == '123' and userpwd == '456':
                print('登录成功！')
                return render_template('success.html')
            else:
                print('用户名和密码不一致！')
                return render_template('index.html', img=captcha, message='用户名和密码不一致！')


# 生成验证码函数
def gencaptcha():
    idx = random.randint(0, 3)
    print(idx)

    global captcha
    captcha = captcha_list[idx]
    print(captcha)


if __name__ == '__main__':
    app.run(debug=False)
